<!DOCTYPE html>
<html>

<head>
    <title>File Upload Example</title>
    <style>
        .image-preview {
            max-width: 100px;
            max-height: 100px;
        }

        .tag {
            display: inline-block;
            background-color: #f1f1f1;
            padding: 2px 5px;
            margin: 2px;
            border-radius: 3px;
        }

        .tag-delete {
            cursor: pointer;
            color: red;
            margin-left: 5px;
        }

        .pagination {
            margin-top: 20px;
        }
        .pagination button {
            margin: 0 5px;
        }
    </style>
</head>

<body>
    <h1>File Management</h1>

    <h2>Upload File</h2>
    <input type="file" id="fileInput" />
    <input type="text" id="nameInput" placeholder="Name" />
    <input type="text" id="typeInput" placeholder="Type" />
    <button onclick="uploadFile()">Upload</button>

    <h2>Download File</h2>
    <input type="text" id="urlInput" placeholder="Type" />
    <button onclick="downloadFile()">Download</button>

    <h2>File List</h2>
    <table id="imageTable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Size</th>
                <th>Image</th>
                <th>Tags</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <div class="pagination">
        <button id="prevPage">Previous</button>
        <span id="pageInfo"></span>
        <button id="nextPage">Next</button>
        <span id="totalNum"></span>
    </div>

    <script>
        let allTags = [];
        let currentPage = 1;
        let itemsPerPage = 10;
        let totalImages = 0;

        const downloadFile = async () => {
            const urlInput = document.getElementById('urlInput');
            try {
                const response = await fetch('/mps/download?url=' + encodeURIComponent(urlInput.value));
                if (response.ok) {
                    console.log('File download successfully');
                    await fetchAndRenderImages();
                } else {
                    throw new Error('Error fetching images');
                }
            } catch (error) {
                console.error(error);
            }
        }

        const uploadFile = async () => {
            const fileInput = document.getElementById('fileInput');
            const nameInput = document.getElementById('nameInput');
            const typeInput = document.getElementById('typeInput');

            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            formData.append('name', nameInput.value);
            formData.append('type', typeInput.value);

            try {
                const response = await fetch('/mps/upload', {
                    method: 'POST',
                    body: formData,
                });

                if (response.ok) {
                    console.log('File uploaded successfully');
                    await fetchAndRenderImages();
                } else {
                    throw new Error('Error uploading file');
                }
            } catch (error) {
                console.error(error);
            }
        };

        const fetchAndRenderImages = async () => {
            try {
                // const response = await fetch('/mps/images');
                const response = await fetch(`/mps/images?page=${currentPage}&limit=${itemsPerPage}`);
                if (response.ok) {
                    // const { data } = await response.json();
                    const { data, total } = await response.json();
                    totalImages = total;
                    renderImages(data);
                    updatePagination();
                } else {
                    throw new Error('Error fetching images');
                }
            } catch (error) {
                console.error(error);
            }
        };

        const updatePagination = () => {
            const totalPages = Math.ceil(totalImages / itemsPerPage);
            document.getElementById('totalNum').textContent = "Total: " + totalImages;
            document.getElementById('pageInfo').textContent = `Page ${currentPage} of ${totalPages}`;
            document.getElementById('prevPage').disabled = currentPage === 1;
            document.getElementById('nextPage').disabled = currentPage === totalPages;
        };

        document.getElementById('prevPage').addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                fetchAndRenderImages();
            }
        });

        document.getElementById('nextPage').addEventListener('click', () => {
            const totalPages = Math.ceil(totalImages / itemsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                fetchAndRenderImages();
            }
        });

        const fetchTags = async () => {
            try {
                const response = await fetch('/mps/tags');
                if (response.ok) {
                    allTags = await response.json();
                } else {
                    throw new Error('Error fetching tags');
                }
            } catch (error) {
                console.error(error);
            }
        };

        const renderImages = (images) => {
            const tableBody = document.getElementById('imageTable').getElementsByTagName('tbody')[0];
            tableBody.innerHTML = '';

            images.forEach(image => {
                const row = document.createElement('tr');

                const nameCell = document.createElement('td');
                nameCell.textContent = image.name;
                row.appendChild(nameCell);

                const sizeCell = document.createElement('td');
                sizeCell.textContent = image.size;
                row.appendChild(sizeCell);

                const imageCell = document.createElement('td');
                const imagePreview = document.createElement('img');
                imagePreview.src = `/pic/${image.thumbnail}`;
                imagePreview.alt = 'Image';
                imagePreview.classList.add('image-preview');
                imageCell.appendChild(imagePreview);
                row.appendChild(imageCell);

                const tagsCell = document.createElement('td');
                image.tags.forEach(tag => {
                    const tagSpan = document.createElement('span');
                    tagSpan.textContent = tag.name;
                    tagSpan.classList.add('tag');
                    const deleteSpan = document.createElement('span');
                    deleteSpan.textContent = 'x';
                    deleteSpan.classList.add('tag-delete');
                    deleteSpan.onclick = () => removeTag(image._id, tag);
                    tagSpan.appendChild(deleteSpan);
                    tagsCell.appendChild(tagSpan);
                });
                const tagSelect = document.createElement('select');
                allTags.forEach(tag => {
                    if (!image.tags.some(existingTag => existingTag._id === tag._id)) {
                        const option = document.createElement('option');
                        option.value = tag._id;
                        option.textContent = tag.name;
                        tagSelect.appendChild(option);
                    }
                });
                const addTagButton = document.createElement('button');
                addTagButton.textContent = 'Add Tag';
                addTagButton.onclick = () => addTag(image._id, tagSelect.value);
                tagsCell.appendChild(tagSelect);
                tagsCell.appendChild(addTagButton);
                row.appendChild(tagsCell);

                const actionsCell = document.createElement('td');
                const deleteButton = document.createElement('button');
                deleteButton.textContent = 'Delete';
                deleteButton.onclick = () => deleteImage(image._id);
                actionsCell.appendChild(deleteButton);
                row.appendChild(actionsCell);

                tableBody.appendChild(row);
            });
        };

        const deleteImage = async (id) => {
            try {
                const response = await fetch(`/mps/images/${id}`, {
                    method: 'DELETE',
                });

                if (response.ok) {
                    console.log('Image deleted successfully');
                    await fetchAndRenderImages();
                } else {
                    throw new Error('Error deleting image');
                }
            } catch (error) {
                console.error(error);
            }
        };

        const addTag = async (id, tagId) => {
            try {
                const response = await fetch(`/mps/images/${id}/tags`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ tagId }),
                });

                if (response.ok) {
                    console.log('Tag added successfully');
                    await fetchAndRenderImages();
                } else {
                    throw new Error('Error adding tag');
                }
            } catch (error) {
                console.error(error);
            }
        };

        const removeTag = async (id, tag) => {
            try {
                const response = await fetch(`/mps/images/${id}/tags`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ tagId: tag._id }),
                });

                if (response.ok) {
                    console.log('Tag removed successfully');
                    await fetchAndRenderImages();
                } else {
                    throw new Error('Error removing tag');
                }
            } catch (error) {
                console.error(error);
            }
        };

        fetchTags().then(fetchAndRenderImages);
    </script>
</body>

</html>